<?php namespace Admin\Controller;
use Hdphp\Controller\Controller;
// 网站配置管理控制器
class WebsetController extends CommonController{
	private $model;
	public function __init(){
		//调用CommonController里面的构造函数
		parent::__init();
		//实例化webset模型
	  	$this->model = new \Common\Model\Webset;
	}
	public function index(){
		
		if(IS_POST){
//		    p(Q("post."));exit;
			foreach(Q("post.") as $name => $value){
				$this->model->where("name='{$name}'")->save(array('value'=>$value));
			}
			//代码合法化
			$data = "<?php\r\nreturn ". var_export(Q("post."),true) ."?>";
			//写入
			file_put_contents('./Config/webset.php', $data);
			View::success('修改成功','index');
		}

		//获得所有数据
		$data = $this->model->get();
		//分配数据
		View::with('data',$data);
		//载入模板
		View::make();
	}
	
	
	
	
	//网站导航
	public function sitenav(){
		
		//获取商品分类 数据
		$gcateModel = new \Common\Model\Gcate;
		$gcateData = $gcateModel->get();
		//把数据变为树状结构
		$gcateData = Data::tree($gcateData,'cate_name','cate_id','p_id');//递归，多层。
		View::with('gcateData',$gcateData);
		
		//载入数据库
		$data = include "./Config/sitenav.php";
		
		//数组反转
		//$data = array_reverse($data,true);
		//返回 数组的键名
//		$data = max(array_keys($data));
//		p($data);
		//p($data);exit;
		View::with('data',$data);
		View::make();
	}
//private static $id=0;
	//添加（异步请求）
	public function add(){
		
		//p(Q("post."));exit;

/*		static $i=0;
		$i+=1;*/
		//载入数据库
		$data = include "./Config/sitenav.php";
		//$data = max(array_keys($data));
//		$_POST['id']  = $data;
		$data[]  = $_POST;
		
		
		$phpCode = "<?php return " . var_export($data,true) . "?>";
		file_put_contents('./Config/sitenav.php', $phpCode);
		echo json_encode($_POST);
	}
	//编辑
	public function edit(){
		//载入数据库
		$data = include "./Config/sitenav.php";
		
		$id = Q('get.id',0,'intval');
		$oldData = $data[$id];
		
		if(IS_POST){
		   // p(Q("post."));
		    //修改
			$data[$id] = $_POST;
			//重写写入数据库
			$code = "<?php return " . var_export($data,true) . "?>";
			file_put_contents('./Config/sitenav.php', $code);
			
			View::success('编辑成功',U('Webset/sitenav'));
		}
		
		//获取商品分类 数据
		$gcateModel = new \Common\Model\Gcate;
		$gcateData = $gcateModel->get();
		//把数据变为树状结构
		$gcateData = Data::tree($gcateData,'cate_name','cate_id','p_id');//递归，多层。
		View::with('gcateData',$gcateData);
		

		View::with('oldData',$oldData);
		View::make('edit_sitenav');
	}
	
	//删除
	public function del(){
		//载入数据库
		$data = include "./Config/sitenav.php";
		$id = Q('get.id',0,'intval');
		//删除一条数据
		unset($data[$id]);
		//p($data);exit;
		//重写写入数据库
		$phpCode = "<?php return " . var_export($data,true) . "?>";
		file_put_contents('./Config/sitenav.php', $phpCode);
		
		View::success('删除成功',U('Webset/sitenav'));
	}	
	
	
	
	
	
	
	
 }
 ?>